<template>
  <div>
    <el-form ref="deptForm" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
          <el-option
            v-for="item in list"
            :key="item.id"
            :value="item.username"
            :label="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="doSubmit">确定</el-button>
        <el-button size="small" @click="$emit('close')">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getEmployeesData } from '@/api/employees'
import { addDepartments, delDepartments, getByDepart } from '@/api/departments'
export default {
  name: 'VueHrDeptDialag',
  // 接收父组件传递过来的数据
  props: {
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }
  },

  data() {
    // 判断编码是否重复
    // 自定义验证
    const validCode = (rule, value, callback) => {
      console.log(value, 'value')
      let existCodeList = this.originList.map(item => item.code)
      // 编辑状态 先移出自己本身的编码
      if (this.isEdit) {
        existCodeList = this.originList.filter(item => item.id !== this.id).map(item => item.code)
      }
      if (existCodeList.includes(value)) {
        // 存在，抛出错误，提示用户编码已存在
        callback(new Error(`编码：${value}已存在`))
      } else {
        callback() // 放行
      }
    }
    // 判断名称是否是重复的
    const validName = (rule, value, callback) => {
      // const existNameList = this.originList.map(item => item.name)

      let existNameList = this.originList.filter(item => item.pid === this.id).map(item => item.name)
      // 编辑的话就先除去自己本身的名称
      // 判断是否是编辑
      if (this.isEdit) {
        // 先取出 id 是 点击的那个
        const current = this.originList.find(item => item.id === this.id)
        const pid = current.pid
        // 找所有pid 相同的兄弟
        const border = this.originList.filter(item => item.pid === pid)
        // 将自己清楚
        existNameList = border.filter(item => item.id !== this.id).map(item => item.name)
      }
      if (existNameList.includes(value)) {
        callback(new Error(`名称${value}已存在`))
      } else {
        callback() // 放行
      }
    }
    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      // 获取部门负责人
      list: [],
      // 表单校验
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 1, max: 50, message: '请输入1-50为字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 1, max: 50, message: '请输入1-50为字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }

        ],
        manager: [
          { required: true, message: '请输入部门负责人', trigger: 'blur' }

        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 1, max: 300, message: '请输入1-300为字符', trigger: 'blur' }

        ]
      }
    }
  },

  mounted() {

  },
  created() {
    this.loadEmployeesData()
    // 如果是 编辑的话
    if (this.isEdit) {
      this.loadByDepart()
    }
  },

  methods: {
    // 发送编辑请求
    async loadByDepart() {
      try {
        const res = await getByDepart(this.id)
        // 回显数据
        // console.log(res)
        this.form = res.data
      } catch (error) {
        console.log(error)
      }
    },
    // 发送请求获取部门负责人
    async loadEmployeesData() {
      try {
        const res = await getEmployeesData()
        // console.log(res.data)
        this.list = res.data
        // console.log(this.list, '111')
      } catch (error) {
        console.log(error)
      }
    },
    doSubmit() {
      // this.hdoSubmit()
      // 兜底校验
      this.$refs.deptForm.validate((valid) => {
        if (!valid) return
        // this.isEdit?'编辑操作'：'新增操作'
        this.isEdit ? this.doEdit() : this.hdoSubmit()
      })
    },
    // 编辑部门
    async doEdit() {
      // 发送请求 修改内容
      try {
        const res = await delDepartments(this.form)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 子传父
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 发送添加请求
    async  hdoSubmit() {
      try {
        const res = await addDepartments({ ...this.form, pid: this.id })
        // console.log(res.code, '111')
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 子传父
        this.$emit('success')
      } catch (error) {
        // this.$message.error(error)
        console.log(error)
      }
    },
    // 点击关闭弹窗清空表单
    reseForm() {
      this.$refs.deptForm.resetFields()
    }

  }
}
</script>

<style lang="scss" scoped>

</style>
